//
//  ListViewController.m
//  Nerdfeed
//
//  Created by Rafal Rebacz on 7/10/13.
//  Copyright (c) 2013 Rafal Rebacz. All rights reserved.
//

#import "ListViewController.h"
#import "RSSChannel.h"
#import "RSSItem.h"
#import "WebViewController.h"
#import "RSSItemTableViewCell.h"
#import "ChannelViewController.h"

@implementation ListViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    
    if (self)
    {
        UIBarButtonItem *bbi= [[UIBarButtonItem alloc] initWithTitle:@"Info"
                                                               style:UIBarButtonItemStyleBordered
                                                              target:self
                                                              action:@selector(showInfo:)];
        [[self navigationItem] setRightBarButtonItem:bbi];
        
        [self fetchEntries];
    }
    
    return self;
}

- (void)viewDidLoad
{
    UINib *nib = [UINib nibWithNibName:@"RSSItemTableViewCell" bundle:nil];
    [[self tableView] registerNib:nib forCellReuseIdentifier:@"RSSItemTableViewCell"];
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
        return YES;
    
    return toInterfaceOrientation == UIInterfaceOrientationPortrait;
}

#pragma mark UITableView delegate methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_channel items] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RSSItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RSSItemTableViewCell"];
    
    if(cell == nil)
    {
        cell = [[RSSItemTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RSSItemTableViewCell"];
    }
    
    RSSItem *item = [[_channel items] objectAtIndex:indexPath.row];
    [cell setCellData:item];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(![self splitViewController])
        [[self navigationController] pushViewController:_webViewController animated:YES];
    else
    {
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:_webViewController];
        NSArray *vcs = @[[self navigationController], nav];
        
        [[self splitViewController] setViewControllers:vcs];
        [[self splitViewController] setDelegate:_webViewController];
    }
    
    RSSItem *entry = [[_channel items] objectAtIndex:indexPath.row];

    [_webViewController listViewController:self handleObject:entry];
}

- (void)fetchEntries
{
    _xmlData = [[NSMutableData alloc] init];
    
    NSURL *url = [NSURL URLWithString:@"http://forums.bignerdranch.com/smartfeed.php?limit=1_DAY&sort_by=standard%20&feed_type=RSS2.0&feed_style=COMPACT"];
    
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    
    _connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
    
}

#pragma mark NSURLConnection delegate methods

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_xmlData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:_xmlData];
    [parser setDelegate:self];
    [parser parse];
    
    _xmlData = nil;
    _connection = nil;
    
    [[self tableView] reloadData];
    NSLog(@"%@\n\n %@\n\n %@\n\n", _channel, [_channel title], [_channel infoString]);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    _connection = nil;
    _xmlData = nil;
    NSString *errorStr = [NSString stringWithFormat:@"Fetch failed: %@", [error localizedDescription]];
    
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error"
                                                 message:errorStr
                                                delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [av show];
}

#pragma mark NSXMLParser delegate methods

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict
{
    NSLog(@"%@ found a %@ element", self, elementName);
    
    if([elementName isEqual:@"channel"])
    {
        _channel = [[RSSChannel alloc] init];
        [_channel setParentParserDelegate:self];

        [parser setDelegate:_channel];
    }
}

- (void)showInfo:(id)sender
{
    ChannelViewController *channelViewController = [[ChannelViewController alloc] initWithStyle:UITableViewStyleGrouped];
    
    if([self splitViewController])
    {
        UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:channelViewController];
        
        NSArray *vcs= @[[self navigationController], nvc];
        [[self splitViewController] setViewControllers:vcs];
        
        [[self splitViewController] setDelegate:channelViewController];
        
        NSIndexPath *selectedRow = [[self tableView] indexPathForSelectedRow];
        
        if(selectedRow)
            [[self tableView] deselectRowAtIndexPath:selectedRow animated:YES];
    }
    else
        [[self navigationController] pushViewController:channelViewController animated:YES];
    
    [channelViewController listViewController:self handleObject:_channel];
}

@end

